//
//  LauEmoticonManager.swift
//  表情包数据
//
//  Created by Lausen on 2017/5/16.
//  Copyright © 2017年 id. All rights reserved.
//

import Foundation
import UIKit

class LauEmoticonManager {
    
    static let shared = LauEmoticonManager()
 
    /// 懒加载表情包的数组
    lazy var pages = [LauEmoticonPageModel]()
    
    /// 利用private来修饰构造函数,可以让外部无法调用,无法利用构造函数来创建对象,很好的保护了单利的创建
    private init() {
        
        loadEmotionResource()
    }
}

// MARK: - 查找表情
extension LauEmoticonManager{
    
    func findEmoticon(picName: String) -> LauEmotionModel? {
        
        for page in pages {
            
            //第一种写法
//            let result = page.emoticons.filter({ (emoticon) -> Bool in
//                
//                return emoticon.chs == picName
//            })

            //第二种写法
            /**
             1:如果函数的最后一个参数是闭包,可以提前结束圆括号
             2:如果闭包里面只有一句话,而且是个返回,那么可以省略掉闭包的格式定义
             3:省略闭包的格式定义之后,参数可以用$0 . $1....来代替第一个参数和第二个参数 ....
             4:可以把return也省略
             综上:就出现了这样一种写法
             */
            let result = page.emoticons.filter(){ $0.chs == picName }
            
            if result.count == 1{
                
                return result[0]
            }
        }
        
        return nil
    }
    
    func emoticonString(str: String, font: UIFont) -> NSAttributedString {
        
        let attributeString = NSMutableAttributedString(string: str)
        
        //1:创建匹配方式 由于 [] 和 () 都是正则的保留符号,所以要转义一下
        let pattern = "\\[.*?\\]"
        
        //2:
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else{
            
            return NSAttributedString(string: "")
        }
        
        
        let matchs = regx.matches(in: str, options: [], range: NSRange(location: 0, length: attributeString.length))
        
        for m in matchs.reversed() {
            
            //1:找到匹配项
            let r = m.rangeAt(0)
            let subStr = (attributeString.string as NSString).substring(with: r)
            
            //2:去替换
            if let em = findEmoticon(picName: subStr){
                
                let attrStr = em.imageText(font: font)
                
                attributeString.replaceCharacters(in: r, with: attrStr)
            }
        }
        

        attributeString.addAttributes(
            [NSForegroundColorAttributeName: UIColor.darkGray,
             NSFontAttributeName: font
            ],
            range: NSRange(location: 0, length: attributeString.length))
        
        return attributeString
    }
}

// MARK: - 加载表情
extension LauEmoticonManager{
    
    // MARK: -- 加载表情的方法
    func loadEmotionResource() {
        
        //1:先获取路径
        guard let path = Bundle.main.path(forResource: "Emoticons.bundle", ofType: nil),
            //2:根据路径,创造一个bundle
              let bundle = Bundle.init(path: path),
            //3:根据bundle加载plist文件
              let resourcePath = bundle.path(forResource: "emoticons.plist", ofType: nil),
            ///根据资源路径加载字典
              let array = NSArray(contentsOfFile: resourcePath) as? [[String: String]],
            //4:守护一下字典转模型的模型数组
              let models = NSArray.yy_modelArray(with: LauEmoticonPageModel.self, json: array) as? [LauEmoticonPageModel]
            else{
            
            return
        }
        
        pages += models
    }
}
